package com.atguigu.flink0624.chapter11;

import com.atguigu.flink0624.bean.WaterSensor;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;

import static org.apache.flink.table.api.Expressions.$;

// 静态导入

/**
 * @Author lizhenchao@atguigu.cn
 * @Date 2021/11/19 10:26
 */
public class Flink01_Table_BaseUse {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);
        DataStreamSource<WaterSensor> waterSensorStream =
            env.fromElements(new WaterSensor("sensor_1", 1000L, 10),
                             new WaterSensor("sensor_1", 2000L, 20),
                             new WaterSensor("sensor_2", 3000L, 30),
                             new WaterSensor("sensor_1", 4000L, 40),
                             new WaterSensor("sensor_1", 5000L, 50),
                             new WaterSensor("sensor_2", 6000L, 60));
    
        // 1. 创建表环境
        StreamTableEnvironment tenv = StreamTableEnvironment.create(env);
        // 2. 把流转成动态表
        Table table = tenv.fromDataStream(waterSensorStream);
        // 3. 在动态表上执行连续查询, 得到结果表(动态表)
        // select * from w where id='sensor_1'
        /*able result = table
            .where("id='sensor_1'")
            .select("id, ts, vc");*/
    
        Table result = table
            .where($("id").isEqual("sensor_1"))
            .select($("id"), $("ts"), $("vc"));
    
        // 4. 把结果表转成流, 输出
        DataStream<WaterSensor> resultStream = tenv.toDataStream(result, WaterSensor.class);
        resultStream.print();
    
        env.execute();
        
    }
}
